package users

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
)

type Users struct {
	User_id      int    `gorm:"primarykey"`
	Username     string `gorm:"size:30"`
	Password     string `gorm:"size:128"`
	Email        string `gorm:"size:50"`
	Phone_number string `gorm:"size:11"`
}

func CheckLogin(username string, password string) (Users, error) {
	var user Users

	// 查询数据库
	database.Gdb.Where("username = ?", username).Find(&user)

	if user.Username == "" {
		return Users{}, errors.New("用户名错误")
	}

	// MD5 加密密码
	hash := md5.Sum([]byte(password))
	encodedPassword := hex.EncodeToString(hash[:])

	// 打印调试信息
	fmt.Println("输入密码加密后:", encodedPassword)
	fmt.Println("数据库中的密码:", user.Password)

	// 比对密码
	if user.Password != encodedPassword {
		return Users{}, errors.New("密码错误")
	}

	return user, nil
}

type UserInfoRegister struct {
	Username     string `gorm:"size:30" form:"username" binding:"required,min=6,max=30"`
	Password     string `gorm:"size:30" form:"password" binding:"required,min=6,max=30"`
	Password2    string `form:"password2" binding:"eqfield=Password"`
	Email        string `gorm:"size:50" form:"email" binding:"email"`
	Phone_Number string `gorm:"size:11" form:"phone" binding:"required"`
	Captcha      string `form:"captcha" binding:"required"`
}

// 验证用户注册信息(并且实现入库)
func CheckRegister(userinfo UserInfoRegister) error {
	var user Users

	database.Gdb.Where("username=?", userinfo.Username).Find(&user)
	if user.User_id != 0 {
		return errors.New("用户名已经存在")
	}
	database.Gdb.Where("email=?", userinfo.Email).Find(&user)
	if user.Email != "" {
		return errors.New("邮箱已经注册过，请换一个邮箱或者找回密码")
	}
	database.Gdb.Where("phone_number=?", userinfo.Phone_Number).Find(&user)
	if user.Phone_number != "" {
		return errors.New("手机号码已经注册过，请换一个手机号码或者找回密码")
	}
	user.Email = userinfo.Email
	hash := md5.Sum([]byte(userinfo.Password))
	user.Password = hex.EncodeToString(hash[:])
	user.Phone_number = userinfo.Phone_Number
	user.Username = userinfo.Username
	database.Gdb.Save(&user)
	return nil

}
